/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.compose.snippets.tgw

import android.graphics.RuntimeShader
import android.os.Build
import android.util.Log
import android.view.MotionEvent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.center
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageShader
import androidx.compose.ui.graphics.LinearGradientShader
import androidx.compose.ui.graphics.RadialGradientShader
import androidx.compose.ui.graphics.Shader
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.input.pointer.motionEventSpy
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.compose.snippets.R
import org.intellij.lang.annotations.Language

/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
 * The snippets in this file relate to the documentation at
 * https://developr.android.com/jetpack/compose/graphics/draw/brush
 *
 * 手电筒效果
 */
@Composable
fun FlashlightExampleScreen(param:String? = "我是传递的参数") {
    Column(Modifier.verticalScroll(rememberScrollState())) {
        Text(text = "传递的参数：$param")
        FlashlightExample()
        Text(text = "改进的方法，手电筒效果：$param")
        FlashlightExample1()

    }
}

@Preview
@Composable
fun FlashlightExample() {
    val imageResource = ImageBitmap.imageResource(LocalContext.current.resources, R.drawable.sunset)
    var pointerOffset by remember {
        mutableStateOf(Offset(0f, 0f))
    }
    Column(
        modifier = Modifier
            .fillMaxWidth(1f)
            .height(500.dp)
            .pointerInput("dragging") {
                detectDragGestures(onDragStart = {
                    //pointerOffset和it类型不同，这里会隐式转换，实现拖转开始点赋值给pointerOffset
                    pointerOffset = it //拖转一定距离后才会触发此处的调用
                    Log.d("tgw2", "onDragStart:${pointerOffset.toString()} ")

                })  { change, dragAmount ->
                    pointerOffset += dragAmount
                }
            }
            .onSizeChanged {
                pointerOffset = Offset(it.width / 2f, it.height / 2f)
            }
            .drawWithContent {
                drawContent()
                // draws a fully black area with a small keyhole at pointerOffset that’ll show part of the UI.
                drawRect(
                    Brush.radialGradient(
                        listOf(Color.Transparent, Color.Black),
                        center = pointerOffset,
                        radius = 100.dp.toPx(),
                    )
                )
            }
    ) {
        Image(
            painter = painterResource(id = R.drawable.dog),
            contentDescription = stringResource(id = R.string.dog_content_description)
        )
    }
}







@Preview
@Composable
fun FlashlightExample1() {
    val imageResource = ImageBitmap.imageResource(LocalContext.current.resources, R.drawable.dog)

            Column(
                modifier = Modifier
                    .fillMaxWidth(1f)
                    .height(500.dp)
//                    .drawBehind {
//                        drawImage(
//                            image = imageResource,
//                            dstSize = IntSize(size.width.toInt(), size.height.toInt())
//                        )
//                    }
            ) {
                GreetingMotionEventSpy("https://juejin.cn/post/7356437111601758218 ---我们利用MotionEventSpy修复了官网的按下时触点位置不准确或者偏倚太大的问题")
            }

}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun GreetingMotionEventSpy(name: String, modifier: Modifier = Modifier):Any {

    var pointerOffset by remember {  //闭包作用
        mutableStateOf(Offset(0f, 0f))
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pointerInput("dragging") {
                detectDragGestures(onDragStart = {
                    //pointerOffset和it类型不同，这里会隐式转换，实现拖转开始点赋值给pointerOffset
                    pointerOffset = it //拖转一定距离后才会触发此处的调用
                    Log.d("tgw2", "onDragStart:${pointerOffset.toString()} ")

                }) { change, dragAmount ->
                    pointerOffset += dragAmount
                    Log.d("tgw3", "onDrag:${pointerOffset.toString()} ----- change:$change --- dragAmount:$dragAmount ")

                }

            }
            .motionEventSpy {
                if (it.actionMasked == MotionEvent.ACTION_DOWN) {
                    pointerOffset = Offset(it.x, it.y)   //获取按下的位置
                    Log.d("tgw1 ", "motionEventSpy:${pointerOffset.toString()} ")

                }


            }
            .onSizeChanged {
                pointerOffset = Offset(it.width / 2f, it.height / 2f)
                Log.d("tgw ", "onSizeChanged:${pointerOffset.toString()} ")
            }
            .drawWithContent {
                drawContent()//绘制的内容 ，不加这句话，下面最外层的内容无效
                // draws a fully black area with a small keyhole at pointerOffset that’ll show part of the UI.
                drawRect(
                    Brush.radialGradient(
                        listOf(Color.Transparent, Color.Black),
                        center = pointerOffset,
                        radius = 120.dp.toPx(),
                    )
                )
            }
    ) {
        Text(
            text = "Hello $name!,Welcome to use compose",
            modifier = modifier
                .fillMaxWidth()
                .wrapContentHeight(Alignment.CenterVertically)
                .drawWithContent {
                },
            textAlign = TextAlign.Center,
            onTextLayout = {
                Log.d("A", "onTextLayout")
            }
        )
        Image(
            painter = painterResource(id = R.drawable.dog),
            contentDescription = stringResource(id = R.string.dog_content_description)
        )
    }
    return pointerOffset
}



